summaryrefslogtreecommitdiffstats
path: root/src/input_common/helpers/stick_from_buttons.cpp
blob: a6be6dac1bc4d0bb552693b4f8e971b804791ae9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
// SPDX-FileCopyrightText: 2017 Citra Emulator Project
// SPDX-License-Identifier: GPL-2.0-or-later

#include <chrono>
#include <cmath>
#include "common/math_util.h"
#include "common/settings.h"
#include "input_common/helpers/stick_from_buttons.h"

namespace InputCommon {

class Stick final : public Common::Input::InputDevice {
public:
    // Some games such as EARTH DEFENSE FORCE: WORLD BROTHERS
    // do not play nicely with the theoretical maximum range.
    // Using a value one lower from the maximum emulates real stick behavior.
    static constexpr float MAX_RANGE = 32766.0f / 32767.0f;
    static constexpr float TAU = Common::PI * 2.0f;
    // Use wider angle to ease the transition.
    static constexpr float APERTURE = TAU * 0.15f;

    using Button = std::unique_ptr<Common::Input::InputDevice>;

    Stick(Button up_, Button down_, Button left_, Button right_, Button modifier_, Button updater_,
          float modifier_scale_, float modifier_angle_)
        : up(std::move(up_)), down(std::move(down_)), left(std::move(left_)),
          right(std::move(right_)), modifier(std::move(modifier_)), updater(std::move(updater_)),
          modifier_scale(modifier_scale_), modifier_angle(modifier_angle_) {
        up->SetCallback({
            .on_change =
                [this](const Common::Input::CallbackStatus& callback_) {
                    UpdateUpButtonStatus(callback_);
                },
        });
        down->SetCallback({
            .on_change =
                [this](const Common::Input::CallbackStatus& callback_) {
                    UpdateDownButtonStatus(callback_);
                },
        });
        left->SetCallback({
            .on_change =
                [this](const Common::Input::CallbackStatus& callback_) {
                    UpdateLeftButtonStatus(callback_);
                },
        });
        right->SetCallback({
            .on_change =
                [this](const Common::Input::CallbackStatus& callback_) {
                    UpdateRightButtonStatus(callback_);
                },
        });
        modifier->SetCallback({
            .on_change =
                [this](const Common::Input::CallbackStatus& callback_) {
                    UpdateModButtonStatus(callback_);
                },
        });
        updater->SetCallback({
            .on_change = [this](const Common::Input::CallbackStatus& callback_) { SoftUpdate(); },
        });
        last_x_axis_value = 0.0f;
        last_y_axis_value = 0.0f;
    }

    bool IsAngleGreater(float old_angle, float new_angle) const {
        const float top_limit = new_angle + APERTURE;
        return (old_angle > new_angle && old_angle <= top_limit) ||
               (old_angle + TAU > new_angle && old_angle + TAU <= top_limit);
    }

    bool IsAngleSmaller(float old_angle, float new_angle) const {
        const float bottom_limit = new_angle - APERTURE;
        return (old_angle >= bottom_limit && old_angle < new_angle) ||
               (old_angle - TAU >= bottom_limit && old_angle - TAU < new_angle);
    }

    float GetAngle(std::chrono::time_point<std::chrono::steady_clock> now) const {
        float new_angle = angle;

        auto time_difference = static_cast<float>(
            std::chrono::duration_cast<std::chrono::milliseconds>(now - last_update).count());
        time_difference /= 1000.0f;
        if (time_difference > 0.5f) {
            time_difference = 0.5f;
        }

        if (IsAngleGreater(new_angle, goal_angle)) {
            new_angle -= modifier_angle * time_difference;
            if (new_angle < 0) {
                new_angle += TAU;
            }
            if (!IsAngleGreater(new_angle, goal_angle)) {
                return goal_angle;
            }
        } else if (IsAngleSmaller(new_angle, goal_angle)) {
            new_angle += modifier_angle * time_difference;
            if (new_angle >= TAU) {
                new_angle -= TAU;
            }
            if (!IsAngleSmaller(new_angle, goal_angle)) {
                return goal_angle;
            }
        } else {
            return goal_angle;
        }
        return new_angle;
    }

    void SetGoalAngle(bool r, bool l, bool u, bool d) {
        // Move to the right
        if (r && !u && !d) {
            goal_angle = 0.0f;
        }

        // Move to the upper right
        if (r && u && !d) {
            goal_angle = Common::PI * 0.25f;
        }

        // Move up
        if (u && !l && !r) {
            goal_angle = Common::PI * 0.5f;
        }

        // Move to the upper left
        if (l && u && !d) {
            goal_angle = Common::PI * 0.75f;
        }

        // Move to the left
        if (l && !u && !d) {
            goal_angle = Common::PI;
        }

        // Move to the bottom left
        if (l && !u && d) {
            goal_angle = Common::PI * 1.25f;
        }

        // Move down
        if (d && !l && !r) {
            goal_angle = Common::PI * 1.5f;
        }

        // Move to the bottom right
        if (r && !u && d) {
            goal_angle = Common::PI * 1.75f;
        }
    }

    void UpdateUpButtonStatus(const Common::Input::CallbackStatus& button_callback) {
        up_status = button_callback.button_status.value;
        UpdateStatus();
    }

    void UpdateDownButtonStatus(const Common::Input::CallbackStatus& button_callback) {
        down_status = button_callback.button_status.value;
        UpdateStatus();
    }

    void UpdateLeftButtonStatus(const Common::Input::CallbackStatus& button_callback) {
        left_status = button_callback.button_status.value;
        UpdateStatus();
    }

    void UpdateRightButtonStatus(const Common::Input::CallbackStatus& button_callback) {
        right_status = button_callback.button_status.value;
        UpdateStatus();
    }

    void UpdateModButtonStatus(const Common::Input::CallbackStatus& button_callback) {
        const auto& new_status = button_callback.button_status;
        const bool new_button_value = new_status.inverted ? !new_status.value : new_status.value;
        modifier_status.toggle = new_status.toggle;

        // Update button status with current
        if (!modifier_status.toggle) {
            modifier_status.locked = false;
            if (modifier_status.value != new_button_value) {
                modifier_status.value = new_button_value;
            }
        } else {
            // Toggle button and lock status
            if (new_button_value && !modifier_status.locked) {
                modifier_status.locked = true;
                modifier_status.value = !modifier_status.value;
            }

            // Unlock button ready for next press
            if (!new_button_value && modifier_status.locked) {
                modifier_status.locked = false;
            }
        }

        UpdateStatus();
    }

    void UpdateStatus() {
        bool r = right_status;
        bool l = left_status;
        bool u = up_status;
        bool d = down_status;

        // Eliminate contradictory movements
        if (r && l) {
            r = false;
            l = false;
        }
        if (u && d) {
            u = false;
            d = false;
        }

        // Move if a key is pressed
        if (r || l || u || d) {
            amplitude = modifier_status.value ? modifier_scale : MAX_RANGE;
        } else {
            amplitude = 0;
        }

        const auto now = std::chrono::steady_clock::now();
        const auto time_difference = static_cast<u64>(
            std::chrono::duration_cast<std::chrono::milliseconds>(now - last_update).count());

        if (time_difference < 10) {
            // Disable analog mode if inputs are too fast
            SetGoalAngle(r, l, u, d);
            angle = goal_angle;
        } else {
            angle = GetAngle(now);
            SetGoalAngle(r, l, u, d);
        }

        last_update = now;
        Common::Input::CallbackStatus status{
            .type = Common::Input::InputType::Stick,
            .stick_status = GetStatus(),
        };
        last_x_axis_value = status.stick_status.x.raw_value;
        last_y_axis_value = status.stick_status.y.raw_value;
        TriggerOnChange(status);
    }

    void ForceUpdate() override {
        up->ForceUpdate();
        down->ForceUpdate();
        left->ForceUpdate();
        right->ForceUpdate();
        modifier->ForceUpdate();
    }

    void SoftUpdate() {
        Common::Input::CallbackStatus status{
            .type = Common::Input::InputType::Stick,
            .stick_status = GetStatus(),
        };
        if (last_x_axis_value == status.stick_status.x.raw_value &&
            last_y_axis_value == status.stick_status.y.raw_value) {
            return;
        }
        last_x_axis_value = status.stick_status.x.raw_value;
        last_y_axis_value = status.stick_status.y.raw_value;
        TriggerOnChange(status);
    }

    Common::Input::StickStatus GetStatus() const {
        Common::Input::StickStatus status{};
        status.x.properties = properties;
        status.y.properties = properties;

        if (Settings::values.emulate_analog_keyboard) {
            const auto now = std::chrono::steady_clock::now();
            const float angle_ = GetAngle(now);
            status.x.raw_value = std::cos(angle_) * amplitude;
            status.y.raw_value = std::sin(angle_) * amplitude;
            return status;
        }

        status.x.raw_value = std::cos(goal_angle) * amplitude;
        status.y.raw_value = std::sin(goal_angle) * amplitude;
        return status;
    }

private:
    static constexpr Common::Input::AnalogProperties properties{
        .deadzone = 0.0f,
        .range = 1.0f,
        .threshold = 0.5f,
        .offset = 0.0f,
        .inverted = false,
        .toggle = false,
    };

    Button up;
    Button down;
    Button left;
    Button right;
    Button modifier;
    Button updater;
    float modifier_scale{};
    float modifier_angle{};
    float angle{};
    float goal_angle{};
    float amplitude{};
    bool up_status{};
    bool down_status{};
    bool left_status{};
    bool right_status{};
    float last_x_axis_value{};
    float last_y_axis_value{};
    Common::Input::ButtonStatus modifier_status{};
    std::chrono::time_point<std::chrono::steady_clock> last_update;
};

std::unique_ptr<Common::Input::InputDevice> StickFromButton::Create(
    const Common::ParamPackage& params) {
    const std::string null_engine = Common::ParamPackage{{"engine", "null"}}.Serialize();
    auto up = Common::Input::CreateInputDeviceFromString(params.Get("up", null_engine));
    auto down = Common::Input::CreateInputDeviceFromString(params.Get("down", null_engine));
    auto left = Common::Input::CreateInputDeviceFromString(params.Get("left", null_engine));
    auto right = Common::Input::CreateInputDeviceFromString(params.Get("right", null_engine));
    auto modifier = Common::Input::CreateInputDeviceFromString(params.Get("modifier", null_engine));
    auto updater = Common::Input::CreateInputDeviceFromString("engine:updater,button:0");
    auto modifier_scale = params.Get("modifier_scale", 0.5f);
    auto modifier_angle = params.Get("modifier_angle", 5.5f);
    return std::make_unique<Stick>(std::move(up), std::move(down), std::move(left),
                                   std::move(right), std::move(modifier), std::move(updater),
                                   modifier_scale, modifier_angle);
}

} // namespace InputCommon